import { defineComponent, h, ref, reactive, onMounted } from 'vue'
import type { DataTableColumns, SelectOption } from 'naive-ui'
import type { Ref } from 'vue'
import { NButton, NDataTable, NSpin, NPagination, NSwitch, useMessage } from 'naive-ui'
import ExchangeApi from '@/service/api/yang/exchange/list'
import pageStyle from '@/theme/common.module.scss'
import MessageBox from '@/components/nComponents/MessageBox'
import { useApi } from '@/hooks/useApi'
import { useClipboard } from '@vueuse/core'
import Edit from './components/Edit'
import validate from '@/utils/validate'
import TabsApi from '@/service/api/yang/exchange/tabs'
export default defineComponent({
  name: 'FormList',
  setup() {
    const optionsState: {
      tabsOptions: SelectOption[]
    } = reactive({
      tabsOptions: []
    })
    const initOptions = async () => {
      TabsApi.list({}).then(({ data }) => {
        optionsState.tabsOptions = data
      })
    }
    const toast = useMessage()
    const { isSupported, copy } = useClipboard()
    const handPrive = async (row: any) => {
      if (validate.isExternal(row.url)) {
        if (!isSupported.value) {
          toast.error('您的浏览器不支持复制功能!')
          return
        }
        let copyText = ''
        if (row?.jiangkuaihe) {
          copyText = `${row.jiangkuaihe}`
        }
        if (row?.extraction) {
          if (copyText) {
            copyText += '\n'
          }
          copyText += row.extraction
        }
        if (copyText) {
          copy(copyText).then(() => {
            window.open(row.url)
          })
        } else {
          window.open(row.url)
        }
      } else {
        copy(row.url)
      }
    }
    const handFanChange = async (row: any, e: number) => {
      row.loading = true
      const { code, message } = await ExchangeApi.edit({
        ...row,
        isFan: e
      })
      row.loading = false
      if (code !== 200) {
        toast.error(message)
        return
      }
      row.isFan = e
    }
    /**
     *  列表
     * */
    const columns: DataTableColumns<any> = [
      {
        title: '标题',
        key: 'title',
        width: 200
      },
      {
        title: '发布人',
        key: 'userInfo.nickname'
      },
      {
        title: '硬币',
        key: 'marbles'
      },
      {
        title: '购买量',
        key: 'buy_count_count'
      },
      {
        title: '浏览量',
        key: 'views'
      },
      {
        title: '分类',
        key: 'tabInfo.name'
      },
      {
        title: '简介',
        key: 'content',
        ellipsis: {
          tooltip: true
        }
      },
      {
        title: '外联',
        key: 'url',
        render(row) {
          return h('div', [
            h(
              NButton,
              {
                size: 'small',
                type: 'success',
                onClick: () => handPrive(row)
              },
              { default: () => '查看' }
            )
          ])
        }
      },
      {
        title: '举报人数',
        key: 'report_count'
      },
      {
        title: '是否翻车',
        key: 'isFan',
        render(row) {
          return h('div', [
            h(NSwitch, {
              value: row.isFan,
              checkedValue: 1,
              uncheckedValue: 0,
              loading: row.loading,
              size: 'small',
              type: 'success',
              onUpdateValue: (e: number) => handFanChange(row, e)
            })
          ])
        }
      },
      {
        title: '操作',
        key: 'total',
        width: 200,
        render(row, index) {
          return h('div', [
            h(
              NButton,
              {
                size: 'small',
                type: 'warning',
                class: 'ml10',
                onClick: () => handAdd(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                size: 'small',
                class: 'ml10',
                type: 'error',
                onClick: () => handDel(index)
              },
              { default: () => '删除' }
            )
          ])
        }
      }
    ]
    const getData = async (params: any): Promise<any> => {
      const { data } = await ExchangeApi.list(params)
      return data
    }
    const delData = async (params: any): Promise<any> => {
      return ExchangeApi.dels(params)
    }
    const addRef: Ref<any> = ref()
    const { tableInfo, pageChange, sizeChange, fetchData, handAdd, delInfo, handDel, delConfirm } =
      useApi({
        addRef,
        getData,
        delData,
        initForm: {
          name: ''
        }
      })

    onMounted(() => {
      fetchData()
      initOptions()
    })

    const boxSlot: { header: () => JSX.Element; default: () => JSX.Element } = {
      header: () => (
        <div>
          <div class="title">温馨提示</div>
        </div>
      ),
      default: () => (
        <>
          <div class={pageStyle.delBox}>
            <div class="pt-[10px] pb-[10px]">
              <i class="esayIcon esayIcon-jinggao"></i>
              <span class="tip">确认要删除选中数据吗?</span>
            </div>
            <div class="btns flex align-center justify-end">
              <NButton
                secondary
                onClick={() => {
                  delInfo.delShow = false
                }}
              >
                取消
              </NButton>
              <NButton style={{ marginLeft: '10px' }} type="primary" onClick={delConfirm}>
                {delInfo.delLoading && (
                  <NSpin
                    class="mr-[10px]"
                    size={15}
                    stroke="#fff"
                    v-slots={{
                      icon: () => <i class="esayIcon esayIcon-a-jiazaizhongdaxiao text-white"></i>
                    }}
                  />
                )}
                <span>确认删除</span>
              </NButton>
            </div>
          </div>
        </>
      )
    }
    return () => (
      <>
        <div class={pageStyle.pageBasic}>
          <div class="pageBasic-main">
            <div class="pb20">
              <NButton type="success" onClick={() => handAdd()}>
                <i class="esayIcon esayIcon-tianjiawenjianjia"></i>
                <span class="ml-[10px]">添加</span>
              </NButton>
            </div>
            <NDataTable
              loading={tableInfo.listLoading}
              columns={columns}
              data={tableInfo.tableData}
              pagination={false}
            />
            <div class={pageStyle.pagination}>
              <NPagination
                v-model:page={tableInfo.queryForm.pageNo}
                page-count={tableInfo.total}
                page-sizes={tableInfo.pageSizes}
                show-quick-jumper
                show-size-picker
                onUpdatePage={pageChange}
                onUpdatePageSize={sizeChange}
              />
            </div>
          </div>
          <Edit tabsOptions={optionsState.tabsOptions} ref={addRef} onSuccess={fetchData} />
          <MessageBox width={'400px'} v-model={delInfo.delShow} isClose={false} v-slots={boxSlot} />
        </div>
      </>
    )
  }
})
